package com.example.music.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

public class FavoritesDAO {
    private DatabaseHelper dbHelper;

    public FavoritesDAO(Context context) {
        dbHelper = new DatabaseHelper(context);
    }

    // 添加收藏
    public long addFavorite(String songPath) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(DatabaseHelper.COLUMN_SONG_PATH, songPath);
        values.put(DatabaseHelper.COLUMN_ADD_TIME, System.currentTimeMillis());

        // 使用insertWithOnConflict避免重复
        long result = db.insertWithOnConflict(
                DatabaseHelper.TABLE_FAVORITES,
                null,
                values,
                SQLiteDatabase.CONFLICT_IGNORE);

        db.close();
        return result;
    }

    // 移除收藏
    public int removeFavorite(String songPath) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        int result = db.delete(DatabaseHelper.TABLE_FAVORITES,
                DatabaseHelper.COLUMN_SONG_PATH + "=?",
                new String[]{songPath});
        db.close();
        return result;
    }

    // 检查是否已收藏
    public boolean isFavorite(String songPath) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query(DatabaseHelper.TABLE_FAVORITES,
                new String[]{DatabaseHelper.COLUMN_ID},
                DatabaseHelper.COLUMN_SONG_PATH + "=?",
                new String[]{songPath},
                null, null, null);

        boolean isFavorite = cursor != null && cursor.getCount() > 0;
        if (cursor != null) cursor.close();
        db.close();
        return isFavorite;
    }

    // 获取所有收藏歌曲路径
    public List<String> getAllFavoritePaths() {
        List<String> paths = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        Cursor cursor = db.query(DatabaseHelper.TABLE_FAVORITES,
                new String[]{DatabaseHelper.COLUMN_SONG_PATH},
                null, null, null, null,
                DatabaseHelper.COLUMN_ADD_TIME + " DESC");

        if (cursor != null) {
            while (cursor.moveToNext()) {
                paths.add(cursor.getString(0));
            }
            cursor.close();
        }
        db.close();
        return paths;
    }
}